<script setup>
import {useApi} from "../../composables/useApi.js"
import showTost from '@/components/toast/index.js'
import {reactive, ref} from "vue"
import StandardGradeDrawear from "@/pages/platform/components/standardGradeDrawear.vue";
//基本数据list
let list = ref([])
let route = useRoute()

let page = ref(1)
let limit = ref(20)
let total = ref(0)//总数
const selected = ref([])
let queryFrom = ref({page: 1, limit: 20,type: route.query.type, student_id: '', sestudent_namex: '', grade_id: '', class_id: '', examcourse_id: ''})
const dialogTile = ref('新增信息')
const headers = ref([
  {
    title: "年份",
    key: "year",
    align: 'start',
    width: "25%"
  },
  {
    title: "学期",
    align: 'start',
    key: "season",
    width: "25%"
  },
  {
    title: "场次",
    align: 'start',
    key: "interim",
    width: "25%"
  },
  {
    title: "操作",
    align: 'end',
    sortable: false,
    key: "options",
  },
])
if(route.query.type==2){
  headers.value.splice(2,1)
  headers.value.forEach(item=>{
    item.width = '33%'
  })
}
// todo 复制修改列表接口
const getList = async () => {
  const {data} = await useApi('/admin/Api.Examcourse/index').post(queryFrom.value)
  total.value = data.value.data.total
  list.value = data.value.data.data.map(item => {
    return {
      ...item, id: item.examcourse_id
    }
  })
}

const dialogFlag = ref(false)
// 头部表单回调
const onChange = val => {
  let data = JSON.parse(JSON.stringify(val))
  data.birth_time = [data.birth_start_time, data.birth_end_time]
  data.entry_time = [data.entry_start_time, data.entry_end_time]
  queryFrom.value = {...queryFrom.value, ...data}
  getList()
}
const isConfirmDialogVisible = ref(false)
// 删除确认弹窗
const onHandleDelete = async (val) => {
  console.log(val)
  let ids = val.data.map(item => item.examcourse_id).toString()
  console.log(ids)
  const {data} = await useApi('/admin/Api.Examcourse/delete').post({examcourse_id: ids})
  console.log(data.value)
  if (data.value.status == 200) {
    showTost("删除成功", {duration: 3000, type: "success"})
    queryFrom.value.page = 1
    isConfirmDialogVisible.value = false
    if (val.type == 'detail') {
      dialogFlag.value = false
    }
    getList()
  }
}
const selectedItems = ref([]);

// 确认弹窗文本
const confirmMsg = ref('')
const currentOptionData = ref({})

// 打开删除弹窗
const onHandleDialog = (type) => {
  if (type == 'delete') {
    console.log(selectedItems)
    if (selectedItems.value.length == 0) return
    let data = list.value.filter(item => selectedItems.value.find(val => val == item.id))
    console.log(data)
    currentOptionData.value = {
      data: data,
      type: 'list'
    }
    confirmMsg.value = `确认删除${data.map(item => item.title).toString()}的信息吗?`
    isConfirmDialogVisible.value = true
  } else {
    dialogTile.value = '添加信息'
    addDialogFlag.value = true
  }
}
// 详情数据
const detailData = ref({})
const viewDetail = async (item) => {
  console.log(item)
  form.value = JSON.parse(JSON.stringify(item))
  dialogTile.value = '修改信息'
  addDialogFlag.value = true
  // console.log(item)
  // const {data} = await useApi('/admin/Api.Grade/detail').post({grade_id: item.grade_id})
  // console.log(data)
  // detailData.value = data.value.data
  // dialogFlag.value = true
}
// 添加弹窗flag
const addDialogFlag = ref(false)
const refVForm = ref()


// 新增取消回调
const resetForm = () => {
  refVForm.value?.reset()
  addDialogFlag.value = false
}

// 获取当前年份
const currentYear = new Date().getFullYear();

// 生成前后20年的年份数组
const getYearsArray = (currentYear, range) => {
  const years = [];
  for (let i = -range; i <= range; i++) {
    years.push(currentYear + i);
  }
  return years;
};

// 调用函数，传入当前年份和范围20年
const yearsArray = ref(getYearsArray(currentYear, 5))

const valid = ref(false)



const form = ref({
  title: '', //2025年其中考试
  year:null,//年份
  season:null,//春,
  interim:null,//期中/期末
  yearIsFocus: false,
  interimIsFocus:false,
  type:route.query.type
})

const schoolTerm = ref(['春','秋'])
const interimArr = ref(['期中','期末'])
const confirmAddTeacher = async (args) => {

  if (!valid.value) return
  form.value.title =route.query.type==2?`${form.value.year}年${form.value.season}季考试`: `${form.value.year}年${form.value.season}季${form.value.interim}考试`
  if(dialogTile.value == '添加信息'){
    const {data} = await useApi('/admin/Api.Examcourse/add').post(form.value)
    if (data.value.status == 200) {
      refVForm.value?.reset()
      addDialogFlag.value = false
      showTost("新增成功", {duration: 3000, type: "success"})
      queryFrom.value.page = 1
      await  getList()
    } else {
      console.log(data.value.msg)
      showTost(data.value.msg, {duration: 3000, type: "error"})
    }
  }else{
    const {data} = await useApi('/admin/Api.Examcourse/update').post(form.value)
    if (data.value.status == 200) {
      refVForm.value?.reset()
      addDialogFlag.value = false
      showTost("修改成功", {duration: 3000, type: "success"})
      queryFrom.value.page = 1
      await getList()
    } else {
      console.log(data.value.msg)
      showTost(data.value.msg, {duration: 3000, type: "error"})
    }
  }

}
let sexList = ref(['男', '女'])
const onHandleEdit = () => {
  queryFrom.value.page = 1
  getList()
}
const required = (value, name) => !!value || `${name}为必填字段`;

const teacherList = ref([])

getList()
const loading = ref(false)

// 分页回调
const onChangePage = (val) => {
  queryFrom.value.page = val.page
  queryFrom.value.limit = val.limit
  getList()
}
const drawaerDelete = async (val) => {
  console.log(val)
  currentOptionData.value = {
    data: [val],
    type: 'detail'
  }
  confirmMsg.value = `确认删除${val.title}的信息吗`
  isConfirmDialogVisible.value = true
}

</script>

<template>
  <div class="content">

    <!--   Ought to 修改右侧抽屉-->
    <standard-grade-drawear @onHandleDelete="drawaerDelete" :teacherList="teacherList" @onHandleEdit="onHandleEdit"
                            :detailData="detailData" @update:isDrawerOpen="dialogFlag=$event"
                            :is-drawer-open="dialogFlag"></standard-grade-drawear>

    <ConfirmDialog
      :handleData="currentOptionData"
      v-model:isDialogVisible="isConfirmDialogVisible"
      @confirm="onHandleDelete"
      :confirm-msg="confirmMsg"
      :confirmation-question="confirmMsg"
      cancel-msg="Unsubscription Cancelled!!"
    />
    <!--    Ought to 修改顶部检索栏部分-->
    <!-- 头部 -->
    <custom-header title="考试场次管理"
                          button-text="添加信息"
                          showBack="true"
                          @onChange="onChange"
                          @onHandle="onHandleDialog"/>
    <VDataTable
      v-model="selectedItems"
      :headers="headers"
      justify="space-around"
      :items="list"
      :items-per-page="100"
      item-key="id"
      show-select
      class="text-no-wrap my-custom-table"
    >
      <template #item.options="{ item }">
        <div class="d-flex align-center options-right-display">
          <div class="d-flex flex-column ms-3 cursor-pointer">
            <i @click="viewDetail(item)" class="ri-edit-line"></i>
          </div>
        </div>
      </template>
    </VDataTable>
    <PaginationVue
      @onChange="onChangePage"
      :current-page="queryFrom.page"
      :page-size="queryFrom.limit"
      :total="total"
    />
    <!--    添加对话框-->
    <VDialog
      :persistent="true"
      max-width="600"
      :model-value="addDialogFlag"
    >
      <div style="width: 600px;"class="dialog-body">
        <AppDrawerHeaderSection
          :title="dialogTile"
          @cancel="addDialogFlag=false"
        />
        <VDivider/>
        <VCard>
          <PerfectScrollbar
            :options="{ wheelPropagation: false }"
            class="h-60"
          >
            <VCardText>
              <VForm
                v-model="valid"
                ref="refVForm"
                @submit.prevent="confirmAddTeacher"
              >
                <VRow>
                  <VCol cols="6">
                    <VSelect
                      v-model="form.year"
                      :items="yearsArray "
                      item-title="item"
                      item-value="item"
                      placeholder="请选择年份"
                      label="年份"
                      :rules="[(val)=>required(val,'年份')]"
                      class="input-width-height"
                    >
                      <template v-slot:label>
                        <span>年份</span>
                        <span  style="color: red;margin-left: 4px;">*</span>
                      </template>
                    </VSelect>

<!--                    <VTextField-->
<!--                      v-model="form.year"-->
<!--                      label="年份"-->
<!--                      @focus="form.yearIsFocus = true"-->
<!--                      @blur="form.yearIsFocus = false"-->
<!--                      :rules="[(val)=>required(val,'年份')]"-->
<!--                      placeholder="请选择年份"-->
<!--                    >-->
<!--                      <template v-slot:label>-->
<!--                        <span>年份</span>-->
<!--                        <span v-if="form.title||form.titleIsFocus" style="color: red;">*</span>-->
<!--                      </template>-->
<!--                    </VTextField>-->
                  </VCol>
                  <VCol cols="6">
                    <VSelect
                      v-model="form.season"
                      :items="schoolTerm"
                      item-title="item"
                      item-value="item"
                      placeholder="请选择学期"
                      label="学期"
                      :rules="[(val)=>required(val,'学期')]"
                      class="input-width-height"
                    >
                      <template v-slot:label>
                        <span>学期</span>
                        <span  style="color: red;margin-left: 4px;">*</span>
                      </template>
                    </VSelect>

                  </VCol>
                  <VCol cols="6" v-if="route.query.type==1">
                    <VSelect
                      v-model="form.interim"
                      :items="interimArr"
                      item-title="item"
                      item-value="item"
                      placeholder="请选择场次"
                      label="场次"
                      :rules="[(val)=>required(val,'场次')]"
                      class="input-width-height"
                    >
                      <template v-slot:label>
                        <span>场次</span>
                        <span  style="color: red;margin-left: 4px;">*</span>
                      </template>
                    </VSelect>

                  </VCol>
                  <VCol cols="12">
                    <div class="d-flex justify-end">

                      <VBtn
                        color="secondary"
                        type="reset"
                        variant="tonal"
                        class="me-4"
                        @click="resetForm"
                      >
                        取消
                      </VBtn>
                      <VBtn
                        type="submit"
                        color="primary"
                        class="me-4"
                      >
                        确定
                      </VBtn>
                    </div>
                  </VCol>
                </VRow>
              </VForm>
            </VCardText>
          </PerfectScrollbar>
        </VCard>

      </div>
    </VDialog>
  </div>

</template>

<style lang="scss" scoped>
.my-custom-table .v-data-table__header th{
  flex:1
}
</style>
